package com.glsc.ngateway.shortmsg.controller;

import com.glsc.ngateway.common.api.shortmsg.bo.*;
import com.glsc.ngateway.common.api.shortmsg.utils.SendStatus;
import com.glsc.ngateway.common.base.domain.mysql.gateway.shortmsg.NoticeMessageSend;
import com.glsc.ngateway.shortmsg.constant.ShortmsgConstant;
import com.glsc.ngateway.shortmsg.service.ShortMessageService;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("shortMessage")
public class ShortMessageController {

    private static final Logger logger = LoggerFactory.getLogger(ShortMessageController.class);

    @Autowired
    private ShortMessageService shortMessageService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 异步服务
     * 1. 校验
     * 2. 入库
     * 返回唯一ID（手机号+日期时间+1000以内随机数）
     */
    @PostMapping(value = "sendShortMessage")
    public ShortMsgResponse sendShortMessage(HttpServletRequest request, @RequestBody ShortMsgRequest shortMsgRequest) {
        String msgId = shortMessageService.initDbrec(shortMsgRequest.getMobile(), shortMsgRequest.getContext(), shortMsgRequest.getSysid(), request.getRemoteAddr());
        return ShortMsgResponse.instanceOfSuccess(msgId);
    }


    /**
     * 根据消息唯一ID查询是否发送到短信平台，虽然不能保证一定送达用户，但没送达用户的可能性非常非常小
     */
    @GetMapping(value = "getSendStatus")
    public ShortMsgResponse getSendResult(@NotEmpty String messageId) {
        List<NoticeMessageSend> dbrecs = shortMessageService.findByMessageId(messageId);
        if (CollectionUtils.isEmpty(dbrecs)) {
            return ShortMsgResponse.instanceOfFail("数据库中没有查询到messageId为" + messageId + "的记录");
        } else {

            ShortMsgResponse response = new ShortMsgResponse();
            response.setErrCode(ShortMsgResponse.Success);
            response.setErrMsg("Success");

            for (SendStatus ss : SendStatus.values()) {
                if (ss.getCode().equals(dbrecs.get(0).getSendStatus())) {
                    response.getData().put(ShortMsgResponse.data_key_SendStatus, ss.toString());
                    break;
                }
            }
            return response;
//            return ShortMsgResponse.instanceOfSuccess(dbrecs.get(0));
        }
    }


    @PostMapping(value = "sendWeixinMessage")
    public ShortMsgResponse sendWeixinMessage(@RequestBody WeixinMsgRequest weixinMsgRequest) {
        String token = null;
        try {
            logger.info("发送企业微信获取token开始");
            token = (String) redisTemplate.opsForValue().get(ShortmsgConstant.REDIS_WEIXIN_TOKEN);
            if (StringUtils.isEmpty(token)) {
                token = shortMessageService.getAccessToken();
            }
            logger.info("发送企业微信获取token结束。" + token);
        } catch (Exception e) {
            logger.error("发送企业微信获取token异常，有可能是redis的问题。", e);
            token = shortMessageService.getAccessToken();
        }
        if (StringUtils.isEmpty(token)) {
            logger.error("发送企业微信获取token失败，返回结束。");
            return ShortMsgResponse.instanceOfFail("发送企业微信获取token失败");
        }

        String msgid = shortMessageService.sendWeixinMessage(weixinMsgRequest, token);
        if (StringUtils.isEmpty(msgid)) {
            return ShortMsgResponse.instanceOfFail("企业微信发送失败");
        } else {
            return ShortMsgResponse.instanceOfSuccess(msgid);
        }
    }


    @PostMapping(value = "sendRobotMessage")
    public ShortMsgResponse sendRobotMessage(@RequestBody WeixinRobotRequest weixinRobotRequest) {
        String token = null;
        try {
            logger.info("企业微信机器人获取token开始");
            token = (String) redisTemplate.opsForValue().get(ShortmsgConstant.REDIS_WEIXIN_TOKEN);
            if (StringUtils.isEmpty(token)) {
                token = shortMessageService.getAccessToken();
            }
            logger.info("企业微信机器人获取token结束。" + token);
        } catch (Exception e) {
            logger.error("企业微信机器人获取token异常，有可能是redis的问题。", e);
            token = shortMessageService.getAccessToken();
        }
        if (StringUtils.isEmpty(token)) {
            logger.error("企业微信机器人获取token失败，返回结束。");
            return ShortMsgResponse.instanceOfFail("企业微信机器人获取token失败");
        }

        String msgid = shortMessageService.sendRobotMessage(weixinRobotRequest, token);
        if (StringUtils.isEmpty(msgid)) {
            return ShortMsgResponse.instanceOfFail("企业微信发送失败");
        } else {
            return ShortMsgResponse.instanceOfSuccess(msgid);
        }
    }

    /*企微应用消息发送
     * 发送示例：
     【文本类型精简发送示例1】
     {
     "oaUserAccounts":["weizt","zzp"],
     "agentId":"1000071",
     "textContent":"content":"测试微信发送"
     }
     【示例2】支持更丰富的数据类型，如图片等，详细参考：https://developer.work.weixin.qq.com/document/path/90236
     {
     "oaUserAccounts":[
     "weizt"
     ],
     "msgType":"text",
     "agentId":"1000071",
     "text":{
     "content":"测试微信发送"
     }
     }
     * @return
     */
    @SneakyThrows
    @PostMapping(value = "sendAgentMessageGeneric")
    public String sendAgentMessageGeneric(@RequestBody @NotNull MessageGenericVo messageGenericVo) {
        String respone = shortMessageService.sendAgentMessageGeneric(messageGenericVo);
        return respone;
    }

    @SneakyThrows
    @PostMapping(value = "sendAgentMessageGenericBatch")
    public List<String> sendAgentMessageGeneric(@RequestBody  List<MessageGenericVo> messageGenericVo) {
        List<String> respone = messageGenericVo.stream().map(vo-> {
            try {
                return shortMessageService.sendAgentMessageGeneric(vo);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException(e);
            }
        }).collect(Collectors.toList());
        return respone;
    }

    /**新版企微群机器人消息发送，代替原消息队列方式推送
     *
     * * * */
    @PostMapping(value = "sendGroupRobotMessage")
    public String sendGroupRobotMessage(@RequestBody WebhookGenericVo webhookGenericVo) {
        String respone = shortMessageService.sendGroupRobotMessage(webhookGenericVo);
        return respone;
    }


}
